package com.example.seckill.service.impl;

import com.example.seckill.activemq.MQSender;
import com.example.seckill.dao.GoodsMapper;
import com.example.seckill.entity.GoodsRecord;
import com.example.seckill.dao.GoodsRecordMapper;
import com.example.seckill.service.IGoodsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.seckill.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author caesar
 * @since 2020-12-08
 */
@Service
public class GoodsRecordServiceImpl extends ServiceImpl<GoodsRecordMapper, GoodsRecord> implements IGoodsRecordService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private GoodsRecordMapper goodsRecordMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MQSender mqSender;
    @Override
    public String seckillGoods(GoodsRecord goodsRecord) {
        Integer goodsId = goodsRecord.getGoodsId();
        Integer number  = goodsRecord.getNumber();
        // 判断库存是否充足
        long surplusNumber = redisUtil.decr(goodsId.toString(),number);
        if(surplusNumber < 0){
            // 如果不够了，重新加回
            if((surplusNumber + number) > 0){
                redisUtil.incr(goodsId.toString(),number);
            }
            return "数量不足，秒杀失败！！！";
        }
        // 信息入消息队列
        mqSender.send(goodsRecord);
        //goodsRecordMapper.insertGoodsRecord(goodsRecord);
        //goodsMapper.updateGoods(goodsRecord);
        return "已参与抢购，请稍后。。。。。。";
    }

    /**
     *  @Author: caesar
     *  @Date：2020年12月09日 14:12:55
     *  @Description: 查询列表
     */
    @Override
    public List<GoodsRecord> queryGoodsRecordList(Integer userId) {
        return goodsRecordMapper.queryGoodsRecordList(userId);
    }

    /**
     *  @Author: caesar
     *  @Date：2020年12月09日 14:12:08
     *  @Description: 插入数据
     */
    @Override
    public void insertGoodsRecord(GoodsRecord goodsRecord) {
        goodsRecordMapper.insertGoodsRecord(goodsRecord);
    }
}
